package com.hue.gulimailseckill.schedule;

import com.hue.gulimailseckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author 姚凤桥
 * @Date 2022/1/12 11:00
 * @Description: 秒杀的定时任务
 */
@Component
@Slf4j
public class SeckillSchedule {
    private final String seckill_lock = "seckill:lock";
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 每天2点上架最近3天的秒杀商品
     * TODO 幂等性处理:多次调用定时任务不会重复上架商品
     */
//    @Scheduled(cron = "0 0 2 * * ?")
    //任意时刻执行，每3秒执行一次
    @Scheduled(cron = "*/3 * * * * ?")
    public void upload3Days() {
        RLock lock = redissonClient.getLock(seckill_lock);
        //非阻塞的获取一把锁
        boolean isLock = lock.tryLock();
        try {
            if (isLock) {
                log.info("上架秒杀商品...");
                seckillService.upload3Days();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (isLock) {
                lock.unlock();
            }
        }
    }
}
